from app import serializer
from app.models.order import Order
from common.utils.db import TotalNumberSerializer
from marshmallow import (
    fields,
    Schema,
    validates,
    validates_schema,
    ValidationError,
    post_dump,
    post_load,
)

from app.models import db
from app.models.user import User


class OrderBodySerializer(serializer.SQLAlchemySchema):
    class Meta:
        model = Order
        fields = [
            "id",
            "order_id",
            "title",
            "ticket_code",
            "check_code",
            "pirce",
            "site",
            "cinema",
            "create_date",
            "user_id",
        ]


class UserBodySerializer(serializer.SQLAlchemySchema):
    orders = fields.Nested(OrderBodySerializer(many=True))

    class Meta:
        model = User
        fields = ["id", "username", "orders", "email", "viepuser", "superuser"]


class UserDataSerizlizer(serializer.SQLAlchemySchema, TotalNumberSerializer):
    data = fields.Nested(UserBodySerializer(many=True))


class UserInfoQuerySerializer(serializer.SQLAlchemySchema):
    page = fields.Int(default=1)
    per_page = fields.Int(default=10)

    class Meta:
        model = User
        fields = ["username", "order_id", "email", "vipuser", "superuser", "page", "per_page"]

    @validates_schema
    def validate_username(self, data, **kwargs):
        """
        验证用户并返回user_obj
        """
        pass

    @post_load(pass_many=True)
    def get_users(self, data, many, **kwargs):
        page = data.pop("page", 1)
        per_page = data.pop("per_page", 10)

        users = db.session.query(User).filter_by(**data).paginate(page, per_page)

        return users.items, users.total


class UserRegistrationBodySerializer(Schema):
    id = fields.Int()


class UserRegistrationQuerySerializer(Schema):
    username = fields.Str(required=True)
    password = fields.Str(required=True)
    password2 = fields.Str(required=True)
    email = fields.Str(default="")
    activation = fields.Bool(default=True)

    @validates_schema
    def validate(self, data, **kwargs):
        if data.get("password") != data.get("password2") or data.get("username") == -1:
            raise RecursionError

    @post_load
    def save(self, data, many, **kwargs):
        user = User(
            username=data.get("username"),
            password=data.get("password"),
            email=data.get("email"),
            activation=data.get("activation"),
        )

        db.session.add(user)
        db.session.commit()

        return user


class UpdateFiles(Schema):
    # 列表中的文件字段用fields.Function
    file = fields.List(fields.Function)
    name = fields.String()

    @validates_schema
    def validate(self, data, **kwargs):
        print(data)
